import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse
  // AxiosRequestHeaders,
} from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
import { LOGIN_URL } from "@/config";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { message } from "@/hooks/useMessage";
import { setToken } from "@/redux/modules/user";
import { checkStatus } from "./helper/checkStatus";
import { store } from "@/redux";
import { axiosConfigs } from "@/api/config/axiosConfigs.ts";
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
  baseUrlKey?: keyof typeof axiosConfigs; // 确认代理
}

// 创建基础实例
const defaultConfig = axiosConfigs.default;

class RequestHttp {
  service: AxiosInstance;

  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config);

    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        config.loading && showFullScreenLoading();
        // console.log("代理数", config.baseUrlKey);
        if (config.baseUrlKey && axiosConfigs[config.baseUrlKey]) {
          config.baseURL = axiosConfigs[config.baseUrlKey].baseURL;
        }

        // 设置请求头token
        if (config.headers && typeof config.headers.set === "function") {
          // 统一配置表头
          config.headers.set("Authorization", store.getState().user.token);
          config.headers.set("x-access-token", store.getState().user.token);
        }
        // console.log(config)
        return { ...config, headers: config.headers || {} };
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        tryHideFullScreenLoading();

        if (data.code == ResultEnum.OVERDUE) {
          store.dispatch(setToken(""));
          message.error(data.msg);
          window.$navigate(LOGIN_URL);
          return Promise.reject(data);
        }

        if (data.code && data.code !== ResultEnum.SUCCESS) {
          message.error(data.msg);
          return Promise.reject(data);
        }
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();

        if (error.message.indexOf("timeout") !== -1) message.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1) message.error("网络错误！请您稍后重试");

        if (response) checkStatus(response.status);

        if (!window.navigator.onLine) window.$navigate("/500");
        return Promise.reject(error);
      }
    );
  }

  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }

  post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
    return this.service.post(url, params, _object);
  }

  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  // _object: CustomAxiosRequestConfig = { headers: {} as AxiosRequestHeaders }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }

  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

export default new RequestHttp(defaultConfig);
